package cn.kgc.layui.servlet;

import cn.kgc.layui.entity.Authority;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class BaseServlet<T> extends HttpServlet {
    public Class<T> clazz;
    public T t;
//    public BaseServlet() {
//        try {
//            Type superclass = getClass().getGenericSuperclass();
//            ParameterizedType parameterizedType = null;
//            if (superclass instanceof ParameterizedType) {
//                parameterizedType = (ParameterizedType) superclass;
//                Type[] typeArray = parameterizedType.getActualTypeArguments();
//                if (typeArray != null && typeArray.length > 0) {
//                    clazz = (Class<T>) typeArray[0];
//                    t= clazz.newInstance();
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Type superclass = getClass().getGenericSuperclass();
            ParameterizedType parameterizedType = null;
            if (superclass instanceof ParameterizedType) {
                parameterizedType = (ParameterizedType) superclass;
                Type[] typeArray = parameterizedType.getActualTypeArguments();
                if (typeArray != null && typeArray.length > 0) {
                    clazz = (Class<T>) typeArray[0];
                    t= clazz.newInstance();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        // 获取前端传递的参数
        req.setCharacterEncoding("utf-8");
        // 通过响应对象获取输出流
        resp.setContentType("application/json;charset=utf-8");
        String uri=req.getRequestURI();
        String methodName=uri.substring(uri.lastIndexOf('/')+1);
        try {
            //获取泛型T的class
            Class<T> tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            //-----通过beanutil将参数封装到实体类中---
            BeanUtils.populate(t,req.getParameterMap());
            Method method= this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class,tClass);
            method.invoke(this,req,resp,t);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}